// 声破天页面导航管理

document.addEventListener('DOMContentLoaded', function() {
    // 处理所有页面的导航链接
    initCommonNavigation();
    
    // 初始化侧边栏菜单的活跃状态
    highlightCurrentPageInMenu();
    
    // 为所有播放列表项添加跳转事件
    initPlaylistItemLinks();
    
    // 处理所有卡片点击事件
    initCardClickEvents();
    
    // 处理通用音频播放
    setupGlobalAudioPlayer();
    
    // 初始化顶部导航按钮（前进/后退）
    initNavigationButtons();
    
    // 检查登录状态
    checkLoginStatus();
});

// 初始化通用导航元素
function initCommonNavigation() {
    // 确保所有页面链接都有正确的href属性
    // 主导航菜单链接
    const mainNavLinks = {
        'home': 'index.html',
        'search': 'search.html',
        'explore': 'explore.html',
        'library': 'library.html'
    };
    
    // 其他常见链接
    const commonLinks = {
        'profile': 'profile.html',
        'settings': 'settings.html',
        'premium': 'premium.html',
        'about': 'about.html',
        'help': 'help.html',
        'charts': 'charts.html',
        'new-releases': 'new-releases.html',
        'radio': 'radio.html',
        'artist': 'artist.html',
        'album': 'album.html',
        'playlist': 'playlist.html',
        'track': 'track.html',
        'history': 'history.html',
        'following': 'following.html',
        'login': 'login.html',
        'register': 'register.html',
        'payment': 'payment.html'
    };
    
    // 更新所有链接
    fixNavigationLinks(mainNavLinks, '.main-nav a');
    fixNavigationLinks(commonLinks, 'a');
}

// 修正导航链接
function fixNavigationLinks(linkMap, selector) {
    document.querySelectorAll(selector).forEach(link => {
        // 检查链接文本或者属性是否匹配需要修复的链接
        for (const [key, url] of Object.entries(linkMap)) {
            // 检查链接文本、类名、id或data属性是否包含key
            if (link.textContent.toLowerCase().includes(key) || 
                link.classList.contains(key) ||
                link.id.includes(key) ||
                link.getAttribute('data-page') === key) {
                
                // 如果链接是空的或者只是#，则设置正确的URL
                if (!link.getAttribute('href') || link.getAttribute('href') === '#') {
                    link.setAttribute('href', url);
                }
            }
        }
    });
}

// 高亮显示当前页面在菜单中的对应项
function highlightCurrentPageInMenu() {
    // 获取当前页面文件名
    const currentPage = window.location.pathname.split('/').pop();
    
    // 移除所有导航项的active类
    document.querySelectorAll('.nav-item').forEach(item => {
        item.classList.remove('active');
    });
    
    // 如果是首页
    if (currentPage === '' || currentPage === 'index.html') {
        setActiveMenuItem('home');
    } 
    // 搜索页
    else if (currentPage === 'search.html') {
        setActiveMenuItem('search');
    }
    // 探索页
    else if (currentPage === 'explore.html' || currentPage === 'charts.html' || 
             currentPage === 'new-releases.html' || currentPage === 'radio.html') {
        setActiveMenuItem('explore');
    }
    // 音乐库页面
    else if (currentPage === 'library.html' || currentPage === 'playlist.html' || 
             currentPage === 'album.html' || currentPage === 'artist.html' ||
             currentPage === 'track.html') {
        setActiveMenuItem('library');
    }
}

// 设置活跃菜单项
function setActiveMenuItem(menuKey) {
    let selector;
    
    switch(menuKey) {
        case 'home':
            selector = '.nav-item:has(a[href="index.html"])';
            break;
        case 'search':
            selector = '.nav-item:has(a[href="search.html"])';
            break;
        case 'explore':
            selector = '.nav-item:has(a[href="explore.html"])';
            break;
        case 'library':
            selector = '.nav-item:has(a[href="library.html"])';
            break;
        default:
            return;
    }
    
    const menuItem = document.querySelector(selector);
    if (menuItem) {
        menuItem.classList.add('active');
    }
}

// 初始化播放列表项链接
function initPlaylistItemLinks() {
    // 处理侧边栏中的播放列表项
    document.querySelectorAll('.playlist-item').forEach(item => {
        // 检查是否已经有链接元素或已初始化
        if (!item.getAttribute('data-initialized') && !item.querySelector('a')) {
            item.addEventListener('click', function() {
                const playlistTitle = this.querySelector('h3').textContent;
                console.log(`打开播放列表: ${playlistTitle}`);
                window.location.href = `playlist.html?name=${encodeURIComponent(playlistTitle)}`;
            });
            
            // 标记为已初始化
            item.setAttribute('data-initialized', 'true');
        }
    });
    
    // 处理"我喜欢的歌曲"
    const likedSongs = document.querySelector('.liked-songs');
    if (likedSongs && !likedSongs.getAttribute('data-initialized')) {
        likedSongs.addEventListener('click', function() {
            window.location.href = 'playlist.html?name=我喜欢的歌曲&type=liked';
        });
        
        // 标记为已初始化
        likedSongs.setAttribute('data-initialized', 'true');
    }
}

// 初始化卡片点击事件
function initCardClickEvents() {
    document.querySelectorAll('.card, .artist-card, .album-card, .playlist-card').forEach(card => {
        if (!card.getAttribute('data-initialized')) {
            // 播放按钮点击事件
            const playButton = card.querySelector('.play-button');
            if (playButton) {
                playButton.addEventListener('click', function(e) {
                    e.stopPropagation(); // 阻止冒泡，避免触发卡片点击
                    
                    const cardTitle = card.querySelector('h3').textContent;
                    const cardSubtitle = card.querySelector('p') ? card.querySelector('p').textContent : '';
                    const cardImage = card.querySelector('img') ? card.querySelector('img').src : '';
                    
                    console.log(`开始播放: ${cardTitle}`);
                    
                    // 导航到播放器页面
                    navigateToPlayerPage(cardTitle, cardSubtitle, cardImage);
                });
            }
            
            // 卡片点击事件
            card.addEventListener('click', function() {
                const cardTitle = this.querySelector('h3').textContent;
                const cardSubtitle = this.querySelector('p') ? this.querySelector('p').textContent : '';
                
                // 根据不同卡片类型决定跳转目标
                if (this.classList.contains('artist-card') || cardSubtitle.includes('艺术家')) {
                    console.log(`查看艺术家: ${cardTitle}`);
                    window.location.href = `artist.html?name=${encodeURIComponent(cardTitle)}`;
                }
                else if (this.classList.contains('album-card') || cardSubtitle.includes('专辑')) {
                    console.log(`查看专辑: ${cardTitle}`);
                    window.location.href = `album.html?name=${encodeURIComponent(cardTitle)}`;
                }
                else if (this.classList.contains('playlist-card') || cardSubtitle.includes('播放列表')) {
                    console.log(`查看播放列表: ${cardTitle}`);
                    window.location.href = `playlist.html?name=${encodeURIComponent(cardTitle)}`;
                }
                else {
                    // 默认导航到播放器
                    navigateToPlayerPage(cardTitle, cardSubtitle, this.querySelector('img')?.src);
                }
            });
            
            // 标记为已初始化
            card.setAttribute('data-initialized', 'true');
        }
    });
    
    // 初始化曲目列表行点击
    document.querySelectorAll('.track-item').forEach(item => {
        if (!item.getAttribute('data-initialized')) {
            item.addEventListener('click', function(e) {
                // 如果点击的是操作按钮，不触发播放
                if (e.target.closest('.track-actions')) {
                    return;
                }
                
                const trackName = this.querySelector('.track-name')?.textContent;
                const artistName = this.querySelector('.track-artist')?.textContent || 
                                  document.querySelector('.album-artist')?.textContent || '未知艺术家';
                
                if (trackName) {
                    console.log(`播放曲目: ${trackName} - ${artistName}`);
                }
            });
            
            // 标记为已初始化
            item.setAttribute('data-initialized', 'true');
        }
    });
}

// 导航到播放器页面
function navigateToPlayerPage(title, subtitle, imageSrc) {
    // 提取类型（播放列表、歌曲、艺术家等）
    let itemType = 'track';
    let artist = '未知艺术家';
    
    if (subtitle) {
        if (subtitle.includes('播放列表')) {
            itemType = 'playlist';
        } else if (subtitle.includes('艺术家')) {
            itemType = 'artist';
            artist = title;
        } else if (subtitle.includes('专辑')) {
            itemType = 'album';
        } else if (subtitle.includes('•')) {
            // 格式可能是 "艺术家 • 专辑"
            artist = subtitle.split('•')[0].trim();
        } else {
            // 假设subtitle就是艺术家名
            artist = subtitle;
        }
    }
    
    // 构建URL参数
    const params = new URLSearchParams();
    params.append('name', title);
    params.append('type', itemType);
    params.append('artist', artist);
    
    // 如果有图片，添加图片参数
    if (imageSrc) {
        params.append('image', imageSrc);
    }
    
    // 跳转到播放器页面
    window.location.href = `player.html?${params.toString()}`;
}

// 设置全局音频播放器
function setupGlobalAudioPlayer() {
    // 检查是否已存在全局音频实例
    if (!window.globalAudioPlayer) {
        window.globalAudioPlayer = new Audio();
        window.globalAudioPlayer.volume = 0.7; // 默认音量
        
        // 加载之前保存的音频状态
        const savedAudioState = localStorage.getItem('audioPlaybackState');
        if (savedAudioState) {
            try {
                const state = JSON.parse(savedAudioState);
                if (state.src) {
                    window.globalAudioPlayer.src = state.src;
                    window.globalAudioPlayer.currentTime = state.currentTime || 0;
                }
            } catch (error) {
                console.error('恢复音频状态失败:', error);
            }
        }
        
        // 页面关闭前保存音频状态
        window.addEventListener('beforeunload', function() {
            try {
                const audioState = {
                    src: window.globalAudioPlayer.src,
                    currentTime: window.globalAudioPlayer.currentTime,
                    isPlaying: !window.globalAudioPlayer.paused
                };
                localStorage.setItem('audioPlaybackState', JSON.stringify(audioState));
            } catch (error) {
                console.error('保存音频状态失败:', error);
            }
        });
    }
}

// 页面离开前保存播放状态
window.addEventListener('beforeunload', function() {
    // 保存当前播放状态，以便在其他页面能继续
    if (window.audioPlayer) {
        // 保存是否在播放
        localStorage.setItem('wasPlaying', !window.audioPlayer.paused);
        
        // 保存当前播放时间
        localStorage.setItem('currentPlayTime', window.audioPlayer.currentTime);
        
        // 保存当前音量
        localStorage.setItem('currentVolume', window.audioPlayer.volume);
        localStorage.setItem('isMuted', window.audioPlayer.muted);
        
        // 保存当前播放歌曲信息
        if (window.playerState && window.playerState.currentTrack) {
            localStorage.setItem('currentTrack', JSON.stringify(window.playerState.currentTrack));
        }
    }
});

// 恢复播放状态（在页面加载时调用）
function restorePlaybackState() {
    if (window.audioPlayer) {
        // 恢复播放时间
        const savedTime = localStorage.getItem('currentPlayTime');
        if (savedTime && !isNaN(parseFloat(savedTime))) {
            window.audioPlayer.currentTime = parseFloat(savedTime);
        }
        
        // 恢复音量设置
        const savedVolume = localStorage.getItem('currentVolume');
        if (savedVolume && !isNaN(parseFloat(savedVolume))) {
            window.audioPlayer.volume = parseFloat(savedVolume);
            
            // 更新音量UI
            updateVolumeUI(parseFloat(savedVolume));
        }
        
        // 恢复静音状态
        const wasMuted = localStorage.getItem('isMuted');
        if (wasMuted === 'true') {
            window.audioPlayer.muted = true;
            // 更新静音UI
            updateVolumeUI(0);
        }
        
        // 如果之前正在播放，尝试恢复播放
        const wasPlaying = localStorage.getItem('wasPlaying') === 'true';
        if (wasPlaying) {
            // 由于浏览器可能会阻止自动播放，使用catch处理错误
            window.audioPlayer.play().catch(e => {
                console.log("自动播放失败，需要用户交互:", e);
            });
            
            // 更新播放按钮UI
            if (typeof updatePlayButton === 'function') {
                updatePlayButton(true);
            }
        }
    }
}

// 更新音量UI显示
function updateVolumeUI(volume) {
    const volumeLevel = document.querySelector('.volume-level');
    const volumeHandle = document.querySelector('.volume-handle');
    const volumeBtn = document.querySelector('.volume-control .option-btn i');
    
    if (!volumeLevel || !volumeHandle || !volumeBtn) return;
    
    // 设置音量条位置
    const percent = Math.max(0, Math.min(100, volume * 100));
    volumeLevel.style.width = `${percent}%`;
    volumeHandle.style.left = `${percent}%`;
    
    // 更新图标
    if (volume === 0 || window.audioPlayer && window.audioPlayer.muted) {
        volumeBtn.className = 'fas fa-volume-mute';
    } else if (volume < 0.5) {
        volumeBtn.className = 'fas fa-volume-down';
    } else {
        volumeBtn.className = 'fas fa-volume-up';
    }
}

// 初始化顶部导航按钮
function initNavigationButtons() {
    const backBtn = document.querySelector('.navigation-buttons .nav-btn:first-child');
    const forwardBtn = document.querySelector('.navigation-buttons .nav-btn:last-child');
    
    if (backBtn) {
        backBtn.addEventListener('click', function() {
            window.history.back();
        });
    }
    
    if (forwardBtn) {
        forwardBtn.addEventListener('click', function() {
            window.history.forward();
        });
    }
}

// 检查登录状态
function checkLoginStatus() {
    // 检查两个可能的存储位置
    const currentUserJson = localStorage.getItem('shengpotian_current_user');
    const currentUserJson2 = localStorage.getItem('currentUser');
    
    // 如果两个位置都没有用户数据，则视为未登录
    if (!currentUserJson && !currentUserJson2) {
        console.log('用户未登录，显示登录界面');
        showLoginPrompt();
    } else {
        console.log('用户已登录，显示个人内容');
        
        // 如果只有一个存储位置有数据，则同步到另一个
        if (currentUserJson && !currentUserJson2) {
            localStorage.setItem('currentUser', currentUserJson);
        } else if (!currentUserJson && currentUserJson2) {
            localStorage.setItem('shengpotian_current_user', currentUserJson2);
        }
    }
}

// 初始化导航
document.addEventListener('DOMContentLoaded', function() {
    // 确保页面加载时突出显示当前页面
    highlightCurrentPageInMenu();
    
    // 其他初始化代码...
    initCommonNavigation();
    initPlaylistItemLinks();
    initCardClickEvents();
    setupGlobalAudioPlayer();
    initNavigationButtons();
    checkLoginStatus();
});